package com.jxit0573.android.lib.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.jxit0573.android.lib.R;
import com.jxit0573.android.lib.model.BaseModel;
import com.jxit0573.android.lib.model.JsBridgeInfo;
import com.jxit0573.android.lib.util.DialogUtils;
import com.jxit0573.android.lib.util.JsonUtils;
import com.jxit0573.android.lib.util.ResourceUtils;
import com.jxit0573.android.lib.widget.X5WebView;
import com.qmuiteam.qmui.arch.QMUIFragmentActivity;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import java.util.List;

/**
 * @author jia
 */
public abstract class BaseActivity extends QMUIFragmentActivity {

    private static List<BaseActivity> acts = Lists.newArrayListWithExpectedSize(16);
    private Handler delayHandler = new Handler();
    private long exitTime = 0L;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        acts.add(this);
    }

    @Override
    protected void onDestroy() {
        acts.remove(this);
        super.onDestroy();
    }

    /**
     * 初始化视图
     */
    public abstract void initView();

    /**
     * 初始化数据
     */
    public abstract void initData();

    /**
     * 获取数据
     */
    public abstract void getData();

    /**
     * 展示数据
     */
    public abstract void setData();

    public void startActivity(Class<? extends BaseActivity> cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (bundle != null && bundle.size() > 0) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void startActivityWithFinish(Class<? extends BaseActivity> cls, Bundle bundle) {
        startActivity(cls, bundle);
        finish();
    }

    /**
     * 保留指定的Activity
     */
    public void retainActivity(Class<? extends BaseActivity> cls) {
        for (int i = 0; i < acts.size(); i++) {
            BaseActivity activity = acts.get(i);
            if (!activity.getClass().equals(cls)) {
                activity.finish();
                activity = null;
                acts.remove(i);
                i--;
            }
        }
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Class<? extends BaseActivity> cls) {
        for (int i = 0; i < acts.size(); i++) {
            BaseActivity activity = acts.get(i);
            if (activity.getClass().equals(cls)) {
                activity.finish();
                activity = null;
                acts.remove(i);
                break;
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0; i < acts.size(); i++) {
            BaseActivity activity = acts.get(i);
            activity.finish();
            activity = null;
            acts.remove(i);
            i--;
        }
        acts.clear();
    }

    public void showMsg(BaseModel result) {
        DialogUtils.getInstance().showToast(this, result.getMsg());
    }

    public void showNetworkError() {
        DialogUtils.getInstance().showToast(this, ResourceUtils.getString(this, R.string.network_error));
    }

    /**
     * 全屏
     */
    public void setFullScreen() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 打开系统浏览器
     */
    public void openBrowser(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void postDelayed(Runnable r, long delayMillis) {
        delayHandler.postDelayed(r, delayMillis);
    }

    /**
     * 获取状态栏的高度
     */
    public int getStatusbarHeight() {
        return QMUIStatusBarHelper.getStatusbarHeight(this);
    }

    /**
     * 沉浸式状态栏
     */
    public void translucent() {
        QMUIStatusBarHelper.translucent(this);
    }

    /**
     * 设置状态栏黑色字体图标
     */
    public void setStatusBarLightMode() {
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }

    public void onViewClick(View v) {
        if (v.getId() == R.id.btn_back) {
            onBackPressed();
        }
    }

    public void responseToH5(X5WebView xWvH5, long msgId, String method, int code, JSONObject data, String msg) {
        runOnUiThread(() -> {
            JsBridgeInfo response = new JsBridgeInfo();
            if (msgId != 0) {
                response.setMsgid(msgId);
            }
            response.setMethod(method);
            BaseModel<JSONObject> params = new BaseModel<>();
            params.setCode(code);
            if (data != null && data.size() > 0) {
                params.setData(data);
            }
            if (!TextUtils.isEmpty(msg)) {
                params.setMsg(msg);
            }
            response.setParams(JSONObject.parseObject(JsonUtils.toJson(params)));
            xWvH5.evaluateJavascript("javascript:response(" + JsonUtils.toJson(response) + ")", s -> {
            });
        });
    }

    /**
     * 连续按两次物理返回键退出程序
     */
    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            DialogUtils.getInstance().showToast(this, ResourceUtils.getString(this, R.string.back_twice));
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    private static class MyHandler extends Handler {

        public MyHandler() {
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    }
}
